<?php
namespace app\index\model;

use app\common\model\User as UserModel;
use think\facade\Session;
use think\facade\Cache;

/**
 * 用户模型
 */
class User extends UserModel
{
    /**
     * 用户登录
     */
    public function login($data)
    {
        //账号登录
        if(isset($data['user_name'])){
            if(!captcha_check($data['captcha'])){
                $this->error = '验证码错误';
                return false;
            }
            $filter = [];
            //是否是手机号
            if(is_phone($data['user_name'])){
                $filter['phone'] = $data['user_name'];
            }else{
                $filter['user_name'] = $data['user_name'];
            }
            // 验证用户名是否正确
    		if(!$user = $this->where('status','>',10)->where($filter)->find()){
    		    $this->error = '用户不存在';
                return false;
    		}
    		// 验证密码是否正确
    		if($user['password'] != hema_hash($data['password'])){
    		    $this->error = '密码错误';
                return false;
    		}
        }else{
            //手机验证码登录
            if(Cache::get($data['phone'] . '_' . $data['captcha'])){
                Cache::delete($data['phone'] . '_' . $data['captcha']);
            }else{
                $this->error = '验证码错误';
                return false; 
            }
            // 验证用户名是否正确
    		if(!$user = $this->where('status','>',10)->where('phone',$data['phone'])->find()){
    		    //用户不存在,创建新用户
                if(isset($data['password'])){
                    //注册操作
                    $password = $data['password'];
                }else{
                    $password = get_captcha(6);//登录操作
                }
                $this->save([
            		'user_name' => time(),
    				'password' => hema_hash($password),
    				'phone' => $data['phone'],
    				'status' => 20, //商户管理
    			]);
			    $user = $this->where('status','>',10)->where('phone',$data['phone'])->find();
    		}
        }
		// 保存登录状态
		Session::set('hema_user', [
			'user' => $user,
			'is_login' => true,
		]);
		return true;
    }  
}
